from typing import List, Optional
from sqlalchemy.orm import Session
from sqlalchemy.exc import IntegrityError
from ..models.department import Department as DepartmentModel
from ..models.user import User
from ..models.employee import Employee
from ..schemas.department import DepartmentCreate, DepartmentUpdate
from fastapi import HTTPException, status

class DepartmentService:
    def __init__(self, db: Session):
        self.db = db

    def get_departments(self, skip: int = 0, limit: int = 100) -> List[DepartmentModel]:
        """获取部门列表"""
        return self.db.query(DepartmentModel).offset(skip).limit(limit).all()

    def get_department(self, department_id: int) -> Optional[DepartmentModel]:
        """根据ID获取部门"""
        return self.db.query(DepartmentModel).filter(DepartmentModel.id == department_id).first()

    def get_department_by_name(self, name: str) -> Optional[DepartmentModel]:
        """根据名称获取部门"""
        return self.db.query(DepartmentModel).filter(DepartmentModel.name == name).first()

    def create_department(self, department_data: DepartmentCreate) -> DepartmentModel:
        """创建部门"""
        # 检查部门名称是否已存在
        existing_department = self.get_department_by_name(department_data.name)
        if existing_department:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="部门名称已存在"
            )
        
        # 创建新部门
        db_department = DepartmentModel(**department_data.dict())
        try:
            self.db.add(db_department)
            self.db.commit()
            self.db.refresh(db_department)
            return db_department
        except IntegrityError:
            self.db.rollback()
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="创建部门失败，数据完整性错误"
            )

    def update_department(self, department_id: int, department_data: DepartmentUpdate) -> DepartmentModel:
        """更新部门信息"""
        db_department = self.get_department(department_id)
        if not db_department:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="部门不存在"
            )
        
        # 如果更新了部门名称，检查是否已存在
        if department_data.name and department_data.name != db_department.name:
            existing_department = self.get_department_by_name(department_data.name)
            if existing_department:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="部门名称已存在"
                )
        
        # 更新部门信息
        for key, value in department_data.dict(exclude_unset=True).items():
            setattr(db_department, key, value)
        
        self.db.commit()
        self.db.refresh(db_department)
        return db_department

    def delete_department(self, department_id: int) -> None:
        """删除部门"""
        db_department = self.get_department(department_id)
        if not db_department:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="部门不存在"
            )
        
        # 检查部门下是否有用户或员工
        has_users = self.db.query(User).filter(User.department_id == department_id).first() is not None
        has_employees = self.db.query(Employee).filter(Employee.department_id == department_id).first() is not None
        
        if has_users or has_employees:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="部门下有用户或员工，无法删除"
            )
        
        self.db.delete(db_department)
        self.db.commit()

    def get_department_stats(self, department_id: int) -> dict:
        """获取部门统计信息"""
        db_department = self.get_department(department_id)
        if not db_department:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="部门不存在"
            )
        
        # 统计部门下的用户数量
        user_count = self.db.query(User).filter(User.department_id == department_id).count()
        
        # 统计部门下的员工数量
        employee_count = self.db.query(Employee).filter(Employee.department_id == department_id).count()
        
        return {
            "department_id": department_id,
            "department_name": db_department.name,
            "user_count": user_count,
            "employee_count": employee_count
        }